package com.msb.dongbao.portal.web.advice;

import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import com.msb.dongbao.common.base.TokenException;
import com.msb.dongbao.common.base.result.ResultWrapper;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: mayu
 * @date: 2021年05月27日 10:47
 * 统一异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public ResultWrapper customExceptionHandle() {
        return ResultWrapper.builder().code(301).msg("统一异常").build();
    }

    /**
     * 自定义TokenException处理
     *
     * @param e
     * @return com.msb.dongbao.common.base.result.ResultWrapper
     */
    @ExceptionHandler(TokenException.class)
    public ResultWrapper tokenExceptionHandle(Exception e) {
        return ResultWrapper.getFailBuilder().code(501).msg(e.getMessage()).build();
    }

    /**
     * @param e
     * @return com.msb.dongbao.common.base.result.ResultWrapper
     */
    @ExceptionHandler(KaptchaException.class)
    public ResultWrapper kaptchaExceptionHandle(KaptchaException e) {
        if (e instanceof KaptchaTimeoutException) {
            return ResultWrapper.getFailBuilder().code(502).msg("验证码过期").build();
        } else if (e instanceof KaptchaIncorrectException) {
            return ResultWrapper.getFailBuilder().code(503).msg("验证码不正确").build();
        } else if (e instanceof KaptchaNotFoundException) {
            return ResultWrapper.getFailBuilder().code(503).msg("验证码未找到").build();
        } else {
            return ResultWrapper.getFailBuilder().code(504).msg("验证码渲染失败").build();
        }
    }

    /**
     * @param e
     * @return com.msb.dongbao.common.base.result.ResultWrapper
     */
    @ExceptionHandler(NullPointerException.class)
    public ResultWrapper kaptchaExceptionHandle(NullPointerException e) {
        return ResultWrapper.getFailBuilder().code(505).msg(e.getMessage() + "为空").build();
    }
}
